package org.example.shoppingmall.controller;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import org.example.shoppingmall.entity.User;
import org.example.shoppingmall.service.UserService;
import org.example.shoppingmall.service.impl.UserServiceImpl;
import org.example.shoppingmall.util.JWTUtil;
import org.example.shoppingmall.util.JsonUtils;
import org.example.shoppingmall.util.RedisUtil;
import org.example.shoppingmall.util.ResponseUtil;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.UUID;

@WebServlet("/user/*")
@MultipartConfig
public class UserController extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uri = request.getRequestURI();

        switch (uri) {
            case "/user/register" -> {
                doRegister(request, response);
            }
            case "/user/login" -> {
                doLogin(request, response);
            }
            case "/user/infoRevise" ->{
                doinfoRevise(request,response);
            }
            case "/user/avatar" ->{
                doUpload(request,response);
            }
            case"/user/upGrade" ->{
                doUpGrade(request,response);
            }
            default -> {

            }
        }
    }




    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uri = request.getRequestURI();
        switch (uri) {
            case "/user/getInfo" -> {
                getUserInfo(request, response);
            }
            case "/user/logout" -> {
                doLogout(request, response);
            }
            default -> {

            }
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getHeader("Authorization");
        String userId = null;
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }


            if (userId != null) {
                User user = userService.getUserInfo(token);

                if (user != null) {
                    user.setPassword(null);
                    ResponseUtil.genSuccessResponse(response, "获取用户信息成功", user);
                } else {
                    ResponseUtil.gen404Response(response, "用户不存在");
                }
            }
         else {
            ResponseUtil.gen404Response(response, "未提供Token");
        }
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @throws IOException
     */
    private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getHeader("Authorization");
        if (token != null) {
            if(token.startsWith("Bearer "))
                token = token.substring(7);
            userService.logout(token);
            ResponseUtil.genSuccessResponse(response, "登出成功", null);
        } else {
            ResponseUtil.gen404Response(response, "Token无效");
        }
    }

    /**
     * 登录
     * @param request
     * @param response
     * @throws IOException
     */
    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject json = JsonUtils.getJson(request);
        String username = json.getString("username");
        String password = json.getString("password");

        if (username.isEmpty() || password.isEmpty()) {
            ResponseUtil.gen404Response(response, "账户名和密码不能为空");
            return;
        }

        String token = userService.login(username, password);
        JSONObject responseData = new JSONObject();
        responseData.put("token",token);

        if (token != null) {
            ResponseUtil.genSuccessResponse(response, "登录成功", responseData);
        } else {
            ResponseUtil.gen404Response(response, "用户名或密码错误");
        }
    }

    /**
     * 注册用户
     * @param request
     * @param response
     */
    private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject json = JsonUtils.getJson(request);
        String username = json.getString("username");
        String password = json.getString("password");
        String email = json.getString("email");


        if (username.isEmpty() || password.isEmpty() || email.isEmpty()) {
            ResponseUtil.gen404Response(response, "账户名、密码、邮箱不完整");
            return;
        }

        User user = new User(username, password, email);
        user.setPhone("11111111111");
        user.setAvatar("localhost:8080/avatar.png");
        user.setNickname(username);
        user.setBalance(new BigDecimal("0.0"));
        boolean success = userService.addUser(user);

        if (success) {
            ResponseUtil.genSuccessResponse(response, "注册成功", null);
        } else {
            ResponseUtil.gen500Response(response, "注册失败，是不是账号或者邮箱已被注册");
        }
    }

    /**
     * 修改用户个人信息
     * @param request
     * @param response
     */
    private void doinfoRevise(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject json = JsonUtils.getJson(request);


        String email = json.getString("email");
        String nickname = json.getString("nickname");
        String phone = json.getString("phone");

        if (email.isEmpty() || nickname.isEmpty() || phone.isEmpty()) {
            ResponseUtil.gen404Response(response, "修改信息时不能均为空");
            return;
        }
        if(email==null || nickname == null || phone == null){
            ResponseUtil.gen404Response(response, "修改信息时不能均为空");
            return;
        }

        String userId = null;
        String token = request.getHeader("Authorization");
        if (token != null) {
            if(token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
            boolean success;

            if (userId != null) {

                success = userService.infoRevise(token,email,nickname,phone);
                if (success) {
                    ResponseUtil.genSuccessResponse(response, "修改用户信息成功", true);
                } else {
                    ResponseUtil.gen404Response(response, "用户不存在");
                }
            }
        } else {
            ResponseUtil.gen404Response(response, "未提供Token");
        }
    }

    /**
     *头像上传
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            String token = req.getHeader("Authorization");
            if (token != null) {
                if (token.startsWith("Bearer "))
                    token = token.substring(7);

            }
                Part part = req.getPart("file");

                if (part == null) {
                    resp.getWriter().write("fail");
                } else {
                    String cd = part.getHeader("Content-Disposition");
                    //截取不同类型的文件需要自行判断
                    String disposition = cd.substring(cd.lastIndexOf("=") + 2, cd.length() - 1);
                    String suffix = disposition.substring(disposition.lastIndexOf("."));
                    // 随机的生成uuid，作为文件名的一部分。 加上刚才获取到的后缀作为最终文件名。
                    String filename = UUID.randomUUID() + suffix;
                    // 获取文件上传的位置，绝对路径URL，如果在WEB-INF下则无法被直接访问（更安全）
                    String serverpath = req.getServletContext().getRealPath("upload");
//                System.out.println(serverpath);
                    //不存在文件夹则新建一个
                    File fileDisk = new File(serverpath);
                    if (!fileDisk.exists()) {
                        fileDisk.mkdir();
                    }

                    // 文件的真正绝对路径 = 文件存储位置 + 文件名
                    String fileparts = serverpath + File.separator + filename;
//                System.out.println(fileparts);
                    // 将文件内容写入指定的磁盘位置
                    part.write(fileparts);

                    // 准备给前端返回的文件访问的URL
                    String projectServerPath = req.getScheme() + "://" + req.getServerName() + ":"
                            + req.getServerPort() + req.getContextPath() + "/" + "upload" + "/" + filename;
                    System.out.println(projectServerPath);
                    boolean success;
                    success = userService.uploadAvatar(token,projectServerPath);
                    if (success) {
                        ResponseUtil.genSuccessResponse(resp, "上传头像成功", true);
                    } else {
                        ResponseUtil.gen404Response(resp, "上传头像失败");
                    }

                }
            }catch(IOException e){
                e.printStackTrace();
            }


    }

    /**
     * 用户申请升级
     * @param request
     * @param response
     */
    private void doUpGrade(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getHeader("Authorization");
        String userId = null;
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }

        if (userId != null) {
            boolean success = userService.upGrade(token);

            if (success) {
                ResponseUtil.genSuccessResponse(response, "申请成功", success);
            } else {
                ResponseUtil.gen404Response(response, "申请失败");
            }
        }
        else {
            ResponseUtil.gen404Response(response, "未提供Token");
        }
    }
}
